
mainEntrence();

// 程序主入口
function mainEntrence() {
  sleep(1000);
  deviceInfo();
  eventListener();

  // 选关卡
  //beforeRun();
  //while (true) {
  // 运行主函数
  main();
  //}
}


function eventListener() {
  threads.start(function () {
    // 启用按键监听
    events.observeKey();
    // 监听音量上键按下
    events.onKeyDown("volume_down", function (event) {
      toastLog("程序手动退出");
      threads.shutDownAll();
      exit();
    });
  });
}


function deviceInfo() {
  auto();
  if (!requestScreenCapture()) {
    toast('请求截图失败，程序结束');
    exit();
  }
  // 调整屏幕亮度
  device.setBrightness(0);
}

function main() {
  toast("开始运行");

  startReady();

  // 跑完之后

}

var waitTime = 0;

function startReady(){
  toast("startReady");
  var img = captureScreen();
  var leftBtn = images.pixel(img, checkForResolution(800, 1000, img).positionX, checkForResolution(800, 1000, img).positionY);
  var rightBtn = images.pixel(img, checkForResolution(1630, 1000, img).positionX, checkForResolution(1630, 1000, img).positionY);
  if(colors.isSimilar(leftBtn, "#ffc3fb12")){
    if(colors.isSimilar(rightBtn,"#ffffffff")){
      toast("点击看广告");
      do{
        sleep(1500);
        click(1900,1000);
        img = captureScreen();
        leftBtn = images.pixel(img, checkForResolution(800, 1000, img).positionX, checkForResolution(800, 1000, img).positionY);
      }while(colors.isSimilar(leftBtn, "#ffc3fb12"));
      adPlay();
    }else{
      sleep(1000);
      restartWatchAd();
    }
  }else if(waitTime > 30){
    stop();
  }else{
    sleep(1000);
    waitTime++;
    startReady();
  }
}

function restartWatchAd(){
  toast("restartWatchAd");
  click(2300,400);
  sleep(3000);
  var start = getPointColor(captureScreen(), 2300, 1280);
  if (colors.isSimilar(start, "#ffffffff")) {
    click(2400, 1280);
    sleep(2000);
    startReady();
  }else{
    stop();
  }
}

function adPlay(){
  waitTime = 0;
  sleep(25000);
  var isEnd = false;
  do {
    back();
    sleep(1000);
    var img = captureScreen();
    var continueBtn = images.pixel(img, checkForResolution(1600, 950, img).positionX, checkForResolution(1600, 950, img).positionY);
    if(colors.isSimilar(continueBtn,"#ff2791db",10)){
      click(1600,950);
      sleep(8000);
    }else{
      sleep(3000);
      img = captureScreen();
      var dialogLeft = images.pixel(img, checkForResolution(800, 1000, img).positionX, checkForResolution(800, 1000, img).positionY);
      isEnd = colors.isSimilar(dialogLeft, "#ffc3fb12");
    }
    
  } while (!isEnd);
  toast("广告结束");
  sleep(2000);
  restartWatchAd();
}

function checkForResolution(x, y, img) {
  var width = img.getWidth();
  var height = img.getHeight();
  if (width < height) {
    var e = x;
    x = y;
    y = e;
  }

  return {
    positionX: x,
    positionY: y
  };
}

function getPointColor(img, x, y) {
  var data = checkForResolution(x, y, img);
  return images.pixel(img, data.positionX, data.positionY);
}